﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AGR.Services.Employee;
using AGR.Services.Employee.Contract;
using AGR.Services.Course;
using AGR.Services.Course.Contract;
using AGR.Services;

namespace AGR.Web.Controls.Form.DetailForm
{
    public partial class EmployeeDetail : System.Web.UI.UserControl
    {
        private IEmployeeService _employeeService = new EmployeeService();
        private ITrainerService _trainerService = new TrainerService();
        private ICourseService _courseService = new CourseService();
        private ISubjectService _subjectService = new SubjectService();

        protected void Page_Load(object sender, EventArgs e)
        { }

        #region Public Methods

        public void LoadDetail(string primaryKey)
        {
            var entity = _employeeService.GetEmployee(primaryKey);

            txtEmployeeCode.Text = primaryKey;
            txtHireDate.Text = entity.HireDate.ToString();
            txtFirstName.Text = entity.FirstName;
            txtLastName.Text = entity.LastName;
            txtPostalAddress.InnerText = entity.PostalAddress;
            txtPhysicalAddress.InnerText = entity.PhysicalAddress;
            txtGender.Text = entity.Gender.Equals("M") ? "Male" : "Female";
            txtType.Text = entity.Type;
            txtIdNumber.Text = entity.IdNumber;
            chkIsTrainer.Checked = entity.IsTrainer == true ? true : false;
            lblTrainerSpecialization.Visible = chkIsTrainer.Checked;
            txtTrainerSpecialization.Visible = chkIsTrainer.Checked;
            txtTrainerSpecialization.Text = entity.TrainerSpecialization;

            txtDateCreated.Text = entity.DateCreated.ToString();
            txtUserCreated.Text = entity.UserCreated;
            txtDateModified.Text = entity.DateModified.ToString();
            txtUserModified.Text = entity.UserModified;

            if (chkIsTrainer.Checked)
                this.LoadGrid();
        }

        public void ClearDetail()
        {
            this.Clear();
            LectureGridView.ShowFooter = false;
            LectureGridView.EditIndex = -1;
        }

        #endregion

        #region Button Methods

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            LectureGridView.ShowFooter = true;
            LectureGridView.EditIndex = -1;

            this.LoadGrid();

            DropDownList ddlCourseTitle = (DropDownList)LectureGridView.FooterRow.FindControl("ddlCourseTitle");
            DropDownList ddlSubjectTitle = (DropDownList)LectureGridView.FooterRow.FindControl("ddlSubjectTitle");
            LoadList(ddlCourseTitle, ddlSubjectTitle);
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            bool selected = false;
            int selectCount = 0;
            int deleteCount = 0;
            string succesMessages = string.Empty;
            string errorMessages = string.Empty;
            string employeeCode = txtEmployeeCode.Text;

            IList<ActionResult> results = new List<ActionResult>();

            for (int i = 0; i < LectureGridView.Rows.Count; i++)
            {
                var row = LectureGridView.Rows[i];
                bool isChecked = ((CheckBox)row.FindControl("chkSelect")).Checked;

                if (isChecked)
                {
                    var codes = LectureGridView.DataKeys[i].Values;
                    string courseCode = codes["CourseCode"].ToString();
                    string subjectCode = codes["SubjectCode"].ToString();
                    results.Add(_trainerService.DeleteTrainerFromLecture(employeeCode, courseCode, subjectCode, "Testuser"));
                    selected = true;
                    selectCount++;
                }
            }

            if (selected == false)
            {
                ucMessage.ShowMessage("Please select records for deletion and try again.", Message.Message.MessageType.Information);
                return;
            }

            foreach (ActionResult result in results)
            {
                if (result.Success)
                {
                    succesMessages = result.Message;
                    deleteCount++;
                }
                else
                    errorMessages = result.Message;
            }

            if (!string.IsNullOrEmpty(succesMessages))
                ucMessage.ShowMessage(succesMessages, Message.Message.MessageType.Success);

            if (!string.IsNullOrEmpty(errorMessages))
                ucMessage.ShowMessage(errorMessages + " " + (selectCount - deleteCount) + " records deleted.", Message.Message.MessageType.Error);

            LectureGridView.EditIndex = -1;
            this.LoadGrid();
        }

        #endregion

        #region GridView Methods

        protected void LectureGridView_OnRowCommand(object sender, CommandEventArgs e)
        {
            if (e.CommandName == "Insert")
            {
                string courseCode = ((DropDownList)LectureGridView.FooterRow.FindControl("ddlCourseTitle")).SelectedValue.ToString();
                string subjectCode = ((DropDownList)LectureGridView.FooterRow.FindControl("ddlSubjectTitle")).SelectedValue.ToString();

                var exists = _trainerService.GetLecture(courseCode, subjectCode);

                if (!string.IsNullOrEmpty(exists.EmployeeCode))
                {
                    ucMessage.ShowMessage("Your action could not be completed. A record assigned to trainer code (" + exists.EmployeeCode + ") already exists on the system.", Message.Message.MessageType.Warning);
                    return;
                }

                var result = _trainerService.AddSubjectToLecture(txtEmployeeCode.Text, courseCode, subjectCode, "TestUser");

                if (result.Success)
                {
                    ucMessage.ShowMessage(result.Message, Message.Message.MessageType.Success);
                    LectureGridView.ShowFooter = false;
                    LectureGridView.EditIndex = -1;
                    this.LoadGrid();
                }
                else
                    ucMessage.ShowMessage(result.Message, Message.Message.MessageType.Error);
            }
            else if (e.CommandName == "CancelInsert")
            {
                ucMessage.ClearMessage();
                LectureGridView.ShowFooter = false;
                LectureGridView.EditIndex = -1;
                this.LoadGrid();
            }
        }

        protected void LectureGridView_RowEditing(object sender, GridViewEditEventArgs e)
        {
            ucMessage.ClearMessage();

            LectureGridView.ShowFooter = false;
            LectureGridView.EditIndex = e.NewEditIndex;
            this.LoadGrid();

            DropDownList ddlCourseTitle = (DropDownList)LectureGridView.Rows[e.NewEditIndex].FindControl("ddlCourseTitle");
            DropDownList ddlSubjectTitle = (DropDownList)LectureGridView.Rows[e.NewEditIndex].FindControl("ddlSubjectTitle");
            LoadList(ddlCourseTitle, ddlSubjectTitle);
        }

        protected void LectureGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            LectureGridView.EditIndex = -1;
            this.LoadGrid();
        }

        protected void LectureGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            LectureGridView.PageIndex = e.NewPageIndex;
            LectureGridView.EditIndex = -1;
            this.LoadGrid();
        }

        #endregion

        #region Private Methods

        private void LoadGrid()
        {
            string employeeCode = txtEmployeeCode.Text;

            var lectures = (from lect in _trainerService.GetLectures(employeeCode)
                            join course in _courseService.GetAllCourses()
                            on lect.CourseCode equals course.CourseCode
                            join subject in _subjectService.GetAllSubjects()
                            on lect.SubjectCode equals subject.SubjectCode
                            select new
                            {
                                CourseCode = lect.CourseCode,
                                CourseTitle = course.CourseName,
                                SubjectCode = lect.SubjectCode,
                                SubjectTitle = subject.Title
                            }).ToList();

            if (lectures.Count == 0)
            {
                lectures.Add(new { CourseCode = "12345", CourseTitle = "", SubjectCode = "12345", SubjectTitle = "" });
                LectureGridView.ShowFooter = true;
                LectureGridView.EditIndex = -1;

                LectureGridView.DataSource = lectures;
                LectureGridView.DataBind();
                LectureGridView.Rows[0].Visible = false;

                DropDownList ddlCourseTitle = (DropDownList)LectureGridView.FooterRow.FindControl("ddlCourseTitle");
                DropDownList ddlSubjectTitle = (DropDownList)LectureGridView.FooterRow.FindControl("ddlSubjectTitle");
                LoadList(ddlCourseTitle, ddlSubjectTitle);
            }
            else
            {
                LectureGridView.DataSource = lectures;
                LectureGridView.DataBind();
            }
        }

        private void LoadList(DropDownList ddlCourseTitle, DropDownList ddlSubjectTitle)
        {
            var subjectList = (from list in _subjectService.GetAllSubjects()
                                select new { SubjectCode = list.SubjectCode, Description = list.Title + " - " + list.SubjectCode }).ToList();

            var courseList = (from list in _courseService.GetAllCourses()
                                select new { CourseCode = list.CourseCode, Description = list.CourseName + " - " + list.CourseCode }).ToList();

            ddlCourseTitle.DataSource = courseList;
            ddlCourseTitle.DataTextField = "Description";
            ddlCourseTitle.DataValueField = "CourseCode";
            ddlCourseTitle.DataBind();

            ddlSubjectTitle.DataSource = subjectList;
            ddlSubjectTitle.DataTextField = "Description";
            ddlSubjectTitle.DataValueField = "SubjectCode";
            ddlSubjectTitle.DataBind();
        }

        private void Clear()
        {
            ucMessage.ClearMessage();

            txtEmployeeCode.Text = string.Empty;
            txtHireDate.Text = string.Empty;
            txtFirstName.Text = string.Empty;
            txtLastName.Text = string.Empty;
            txtPostalAddress.InnerText = string.Empty;
            txtPhysicalAddress.InnerText = string.Empty;
            txtGender.Text = string.Empty;
            txtType.Text = string.Empty;
            txtIdNumber.Text = string.Empty;
            chkIsTrainer.Checked = false;
            lblTrainerSpecialization.Visible = false;
            txtTrainerSpecialization.Visible = false;
            txtTrainerSpecialization.Text = string.Empty;

            txtDateCreated.Text = string.Empty;
            txtUserCreated.Text = string.Empty;
            txtDateModified.Text = string.Empty;
            txtUserModified.Text = string.Empty;
        }

        #endregion
    }
}